<template>
	<el-dialog v-model="visible" :title="dataForm.id ? '编辑' : '新建'" :close-on-click-modal="false">
		<!-- <template #body> -->
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
			<el-form-item prop="appName" label="AppName">
				<el-input v-model="dataForm.appName" placeholder="请输入AppName"></el-input>
			</el-form-item>
			<el-form-item prop="title" label="名称">
				<el-input v-model="dataForm.title" placeholder="请输入执行器名称"></el-input>
			</el-form-item>
			<el-form-item prop="sort" label="排序">
				<el-input-number v-model="dataForm.sort" :min="0" :max="9999" placeholder="执行器序号"></el-input-number>
			</el-form-item>
			<el-form-item prop="addressType" label="注册方式">
				<fast-radio-group v-model="dataForm.addressType" dict-type="register_type"></fast-radio-group>
			</el-form-item>
			<el-form-item v-if="dataForm.addressType == 1" prop="ip" label="执行器IP">
				<el-input v-model="dataForm.ip" placeholder="请输入执行器IP" />
			</el-form-item>
			<el-form-item v-if="dataForm.addressType == 1" prop="port" label="端口号">
				<el-input v-model="dataForm.port" placeholder="请输入执行器端口号" />
			</el-form-item>
			<el-form-item v-if="dataForm.addressType == 1" prop="userName" label="用户名">
				<el-input v-model="dataForm.userName" placeholder="请输入执行器用户名" />
			</el-form-item>
			<el-form-item v-if="dataForm.addressType == 1" prop="passWord" label="密码">
				<el-input v-model="dataForm.passWord" show-password type="passWord" placeholder="请输入执行器密码" />
			</el-form-item>
			<el-form-item prop="shellScript" label="执行指令">
				<div style="width: 100%; height: 300px; display: flex; flex-direction: row">
					<div style="flex: 7">
						<ShellStudio v-if="isShellSyudioVisible" ref="shellStudioRef" style="height: 300px; width: 100%"></ShellStudio>
					</div>
					<div style="padding-left: 10px; flex: 1">
						<el-button type="primary" @click="textCmd" style="margin-right: 5px">测试指令</el-button>
						<el-tooltip placement="top">
							<template #content
								>${} 占位符: 后面是自定义值，没有代表取系统默认值
								<br />
								${xpath}: 代表目录占位符 默认是值/root/datax/job/
								<br />
								${xname}: 代表文件名称，默认值系统随机生成。</template
							>
							<el-icon color="#ee9d28"><QuestionFilled /></el-icon>
						</el-tooltip>
					</div>
				</div>
			</el-form-item>
		</el-form>
		<!-- </template> -->
		<template #footer>
			<el-button v-if="dataForm.addressType == 1" type="primary" @click="ipTest()">测试</el-button>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="loading" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import store from '@/store'
import { useCrud } from '@/hooks/indexZXQ.ts'
import { nextTick, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'

import { actuatorPostSubmit, actuatorApi, actuatorCmdTest } from '@/api/task-scheduling'
import { actuatorIpTest } from '@/api/task-scheduling/index5s'
import { ElLoading } from 'element-plus'

import ShellStudio from './shell-studio.vue'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const postList = ref<any[]>([])
const roleList = ref<any[]>([])
const orgList = ref([])
const dataFormRef = ref()

const isShellSyudioVisible = ref(false)
const shellStudioRef = ref()

const dataForm = reactive({
	id: '',
	appName: '',
	title: '',
	sort: 0,
	addressType: '',
	ip: '',
	userName: '',
	passWord: '',
	port: '',
	shellScript: ''
})

const loading = ref(false)

const title = ref('')

const shellScript = ref('')

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	isShellSyudioVisible.value = true

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	dataForm.ip = ''
	dataForm.userName = ''
	dataForm.passWord = ''
	dataForm.port = ''

	nextTick(() => {
		shellStudioRef.value.setEditorValue('')
	})
	if (id) {
		getActuator(id)
	} else {
	}
}

const getActuator = id => {
	actuatorApi(id).then(res => {
		Object.assign(dataForm, res.data)

		if (res.data.shellScript) {
			shellStudioRef.value.setEditorValue(res.data.shellScript)
		}
	})
}

const checkShellScript = (rule: any, value: any, callback: any) => {
	if (!shellScript.value) {
		return callback(new Error('必填项不能为空'))
	} else {
		callback()
	}
}

const dataRules = ref({
	appName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	title: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	addressType: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
	ip: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	port: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	userName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	passWord: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
	shellScript: [{ required: true, validator: checkShellScript }]
})

const textCmd = () => {
	shellScript.value = shellStudioRef.value.getEditorValue()
	if (shellScript.value) {
		const cmdLoading = ElLoading.service({
			lock: true,
			text: '执行指令验证中...... 请稍后',
			background: 'rgba(0, 0, 0, 0.7)'
		})
		actuatorCmdTest({ shellScript: shellScript.value })
			.then(res => {
				cmdLoading.close()
				setTimeout(() => {
					ElMessage({
						message: res.msg,
						type: 'success',
						duration: 500,
						onClose: () => {}
					})
				}, 100)
			})
			.catch(() => {
				cmdLoading.close()
			})
	} else {
		ElMessage({
			message: '请输入执行指令',
			type: 'warning',
			duration: 500
		})
	}
}

// 表单提交
const submitHandle = () => {
	shellScript.value = shellStudioRef.value.getEditorValue()
		? shellStudioRef.value.getEditorValue().replace(/\r/g, '')
		: shellStudioRef.value.getEditorValue()
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			loading.value = false
			return false
		}
		dataForm.shellScript = shellScript.value

		loading.value = true
		actuatorPostSubmit(dataForm)
			.then(res => {
				ElMessage.success({
					message: '操作成功',
					duration: 500,
					onClose: () => {
						loading.value = false
						visible.value = false
						emit('refreshDataList')
					}
				})
			})
			.catch(() => {
				loading.value = false
			})
	})
}

const ipTest = () => {
	if (dataForm.passWord && dataForm.ip && dataForm.userName && dataForm.port) {
		const newData = {
			passWord: dataForm.passWord,
			ip: dataForm.ip,
			userName: dataForm.userName,
			port: dataForm.port,
			id: dataForm.id
		}
		const testLoading = ElLoading.service({
			lock: true,
			text: '连接测试中...... 请稍后',
			background: 'rgba(0, 0, 0, 0.7)'
		})
		actuatorIpTest(newData)
			.then(res => {
				testLoading.close()
				if (res.data.success) {
					ElMessage.success('测试连接成功')
				} else {
					ElMessage.error(res.data.msg)
				}
			})
			.catch(() => {
				testLoading.close()
				ElMessage.error('测试连接失败')
			})
	} else {
		ElMessage.error('请输入执行器IP、端口号、用户名、密码')
	}
}

defineExpose({
	init
})
</script>
